﻿using Consul;
using Developer.Core.FrameWork.RegisterCenter.Options;
using Developer.Core.FrameWork.RegisterCenter.Service;
using Microsoft.Extensions.Options;
using System;

namespace Developer.Core.FrameWork.RegisterCenter.Consul
{
    /// <summary>
    /// Consul服务发现
    /// </summary>
    public class ConsulServiceRegister : IServiceRegister
    {
        /// <summary>
        /// 注册配置选项
        /// </summary>
        private readonly ServiceRegisterOptions serviceRegisterOptions;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="options"></param>
        public ConsulServiceRegister(IOptions<ServiceRegisterOptions> options)
        {
            this.serviceRegisterOptions = options.Value;
        }

        /// <summary>
        /// Consul服务注册
        /// </summary>
        public void Register()
        {
            // 1、建立consul客户端连接
            var consulClient = new ConsulClient(configuration =>
            {
                configuration.Address = new Uri(this.serviceRegisterOptions.RegisterAddress);
            });

            // 2、获取服务注册地址
            var uri = new Uri(this.serviceRegisterOptions.ServiceAddress);

            // 3、创建consul服务注册对象
            var registration = new AgentServiceRegistration()
            {
                ID = string.IsNullOrWhiteSpace(this.serviceRegisterOptions.ServiceId) ? Guid.NewGuid().ToString() : this.serviceRegisterOptions.ServiceId,
                Name = this.serviceRegisterOptions.ServiceName,
                Address = uri.Host,
                Port = uri.Port,
                Tags = this.serviceRegisterOptions.ServiceTags,
                Check = new AgentServiceCheck
                {
                    Timeout=TimeSpan.FromSeconds(10), // 健康检查超时时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), // 服务停止后延迟5秒注销服务
                    HTTP=$"{uri.Scheme}://{uri.Host}:{uri.Port}{this.serviceRegisterOptions.HealthCheckAddress}", // 健康检查地址
                    Interval = TimeSpan.FromSeconds(10) // 健康检查间隔时间
                }
            };

            // 4、注册服务
            consulClient.Agent.ServiceRegister(registration).Wait();

            // 5、关闭连接
            consulClient.Dispose();

            Console.WriteLine("服务注册成功");
        }

        /// <summary>
        /// 注销服务
        /// </summary>
        public void Deregister()
        {
            // 1、创建consul客户端连接
            var consulClient = new ConsulClient(configuration =>
            {
                configuration.Address = new Uri(this.serviceRegisterOptions.RegisterAddress);
            });

            // 2、注销服务
            consulClient.Agent.ServiceDeregister(this.serviceRegisterOptions.ServiceId).Wait();

            // 3、关闭连接
            consulClient.Dispose();
        }

         
    }
}
